<template>
  <div>
    <div :key="componentKey">
      <el-table
          :data="fixtureListData"
          style="width: 100%"
          :height="fixtureListHeight"
          border
          highlight-current-row>

        <!-- 序号 -->
        <el-table-column
            :label="pageVal.fixtureList.order"
            width="60"
            align="center"
            v-slot:default="scope">
          {{scope.$index+1}}
        </el-table-column>
        <!-- 指导书id -->
        <el-table-column
            prop="instruction_id"
            :label="pageVal.fixtureList.instruction_id"
            width="180"
            align="center">
        </el-table-column>
        <!-- 责任部门 -->
        <el-table-column
            prop="department"
            :label="pageVal.fixtureList.department"
            width="125"
            align="center"
            v-slot:default="scope">
                        <span v-if="languageS==='chinese' && scope.row.department!==undefined && scope.row.department.split('/').length===3">
                        {{scope.row.department.split('/')[0]}}</span>
          <span v-else-if="languageS==='english' && scope.row.department!==undefined && scope.row.department.split('/').length===3">
                        {{scope.row.department.split('/')[1]}}</span>
          <span v-else-if="languageS==='russian' && scope.row.department!==undefined && scope.row.department.split('/').length===3">
                        {{scope.row.department.split('/')[2]}}</span>
          <span v-else>{{scope.row.department}}</span>
        </el-table-column>
        <!-- 线体 -->
        <el-table-column
            prop="line"
            :label="pageVal.fixtureList.line"
            width="125"
            align="center"
            v-slot:default="scope">
                        <span v-if="languageS==='chinese' && scope.row.line!==undefined && scope.row.line.split('/').length===3">
                        {{scope.row.line.split('/')[0]}}</span>
          <span v-else-if="languageS==='english' && scope.row.line!==undefined && scope.row.line.split('/').length===3">
                        {{scope.row.line.split('/')[1]}}</span>
          <span v-else-if="languageS==='russian' && scope.row.line!==undefined && scope.row.line.split('/').length===3">
                        {{scope.row.line.split('/')[2]}}</span>
          <span v-else>{{scope.row.line}}</span>
        </el-table-column>
        <!-- 工序/存放地点 -->
        <el-table-column
            prop="op"
            :label="pageVal.fixtureList.op"
            width="120"
            align="center">
        </el-table-column>
        <!-- 检查项目 -->
        <el-table-column
            prop="measurement_project"
            :label="pageVal.fixtureList.measurement_project"
            align="center"
            v-slot:default="scope">
                        <span v-if="languageS==='chinese' && scope.row.measurement_project!==undefined && scope.row.measurement_project.split('|*|').length===3">
                        {{scope.row.measurement_project.split('|*|')[0]}}</span>
          <span v-else-if="languageS==='english' && scope.row.measurement_project!==undefined && scope.row.measurement_project.split('|*|').length===3">
                        {{scope.row.measurement_project.split('|*|')[1]}}</span>
          <span v-else-if="languageS==='russian' && scope.row.measurement_project!==undefined && scope.row.measurement_project.split('|*|').length===3">
                        {{scope.row.measurement_project.split('|*|')[2]}}</span>
          <span v-else>{{scope.row.measurement_project}}</span>
        </el-table-column>
        <!-- 编辑 -->
        <el-table-column
            :label="main.edit"
            align="center"
            width="100px"
            v-slot:default="scope"
            v-if="usePower===111">
          <el-link @click="qrCodeShow(scope.row)">
            <i class="el-icon-s-grid"></i>
          </el-link>
        </el-table-column>
      </el-table>
    </div>
    <!-- 二维码弹窗 -->
    <el-dialog
        :visible.sync="qrCodeDialog"
        width="300px">
      <div class="qr-container">
        <canvas id="qr-canvas" v-if="qrCodeDialog"></canvas>
      </div>
      <div class="qr-info">
        <p style="font-size: medium">{{pageVal.fixtureList.instruction_id}}: {{ currentInstructionId }}</p>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="qrCodeDialog = false" size="mini">关闭</el-button>
      <el-button type="primary" @click="downloadQRCode" size="mini">下载</el-button>
    </span>
    </el-dialog>
  </div>
</template>
<script>
import QRCode from 'qrcode';
export default {
  name: "goodProductConditionsFixtureList",
  data() {
    return {
      componentKey: 0, // 用于强制刷新组件
      //控制工装技术条件表格fixtureList高度的变量
      fixtureListHeight:window.visualViewport.height-250,
      //—————————————————————————————————————————基本信息变量————————————————————————————————————————————
      //用户权限相关的变量
      useName:'',//用户名称
      useId:'',//用户编号
      usePower:'',//用户权限
      //——————————————————————————————————————————语言切换变量———————————————————————————————————————————
      //用户登录后默认为中文
      languageS:'chinese',
      //切换语言，页面变量
      main:{
        edit:'编辑',
      },
      pageVal:{
        cancel:'取 消',
        ok:'确 定',
        sureToDelete:'确定删除数据吗？',
        fixtureList:{
          order:'序号',
          instruction_id:'检查项目id',
          department:'责任部门',
          line:'线体',
          op:'OP/存放地点',
          measurement_project:'检查项目',
        },
      },
      //工装台账大表
      fixtureListData:[{
        department:'',
        instruction_id:'',
        line:'',
        op:'',
        measurement_project:''
      }],
      //二维码弹窗
      qrCodeDialog:false,
      currentInstructionId: '',  //用于生成二维码时记录当前行的编码
    }
  },
  methods:{
    //查询用户信息的函数
    inquiry(){
      //输入用户编号，向后端查询信息
      const useId=localStorage.getItem('userName').replace(/"/g, '');
      this.$request.post('/useQueryPower',{
        queryFiledName:'goodProductCondition',
        userId:useId,
      }).then(result=>{
        if (result.code === 401) {
          this.$router.push('UserLogin')
          alert("您未登录，请登录")
        }else {
          this.useName=result.data.name
          this.usePower=result.data.goodProductCondition
          this.useId=useId
        }
      })
    },
    //选择语言
    changeLanguage(language){
      this.languageS=language
      // 其他语言切换逻辑...
      this.componentKey = !this.componentKey;
      if (language==='chinese'){
        //main
        this.main.edit='编辑'
        //pageVal
        this.pageVal.cancel='取 消'
        this.pageVal.ok='确 定'
        this.pageVal.sureToDelete='确定删除数据吗？'

        this.pageVal.fixtureList.order='序号'
        this.pageVal.fixtureList.instruction_id='检查项目id'
        this.pageVal.fixtureList.department='责任部门'
        this.pageVal.fixtureList.line='线体'
        this.pageVal.fixtureList.op='OP/存放地点'
        this.pageVal.fixtureList.measurement_project='检查项目'
      }
      else if (language==='english') {
        //main
        this.main.edit='Edit'
        //pageVal
        this.pageVal.cancel='Cancel'
        this.pageVal.ok='OK'
        this.pageVal.sureToDelete='Sure to delete the data?'

        this.pageVal.fixtureList.order='Order'
        this.pageVal.fixtureList.instruction_id='Measurement Project-id'
        this.pageVal.fixtureList.department='Department'
        this.pageVal.fixtureList.line='Line'
        this.pageVal.fixtureList.op='OP/Location'
        this.pageVal.fixtureList.measurement_project='Measurement Project'
      }
      else if (language==='russian') {
        //main
        this.main.edit='Правка'
        //pageVal
        this.pageVal.cancel='Отмена'
        this.pageVal.ok='Подтвердить'
        this.pageVal.sureToDelete='Уверен в удалении данных?'

        this.pageVal.fixtureList.order='Заказ'
        this.pageVal.fixtureList.instruction_id='Проект-id'
        this.pageVal.fixtureList.department='Департамент'
        this.pageVal.fixtureList.line='Линия'
        this.pageVal.fixtureList.op='Операция/местоположение'
        this.pageVal.fixtureList.measurement_project='Проект'
      }
    },
    //查询低频作业指导书中"工装点检"
    queryInstructionId(){
      // 先清空现有数据
      this.fixtureListData = [];
      this.inquiryType('工装点检').then(dataList => {
        // 筛选 workshop 为 '装配车间/Assembly workshop/Сборочная линия' 的数据
        const filteredList = dataList.filter(data =>
            data.workshop === '装配车间/Assembly workshop/Сборочная линия'
        );
        // 批量处理筛选后的数据
        const tempList = filteredList.map(data => ({
          department: data.workshop,
          instruction_id: data.id,
          line: data.lineName,
          op: data.op,
          measurement_project: data.fileName
        }));

        // 添加到现有数据中
        this.fixtureListData = [...this.fixtureListData, ...tempList];
        return tempList;
      });
    },
    //辅助函数，依据用户现在的是哪一种作业指导书，筛选出所有的数据来,改造成带有返回值的函数
    async inquiryType(type){
      const result= await this.$request.post('/inquiryType',type)
      if (result.code === 401) {
        this.$router.push('UserLogin')
        alert("您未登录，请登录")
      } else {
        return result.data
      }
    },
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~生成二维码~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 显示二维码弹窗
    qrCodeShow(row) {
      // 检查数据有效性
      if (!row || !row.instruction_id) {
        this.$message.warning('无法生成二维码：数据不完整');
        return;
      }

      this.currentInstructionId = row.instruction_id;
      this.qrCodeDialog = true;

      // 等待对话框完全渲染
      this.$nextTick(() => {
        // 添加短暂延迟确保canvas元素已创建
        setTimeout(() => {
          this.generateQRCode(this.currentInstructionId);
        }, 100);
      });
    },
    // 生成二维码
    generateQRCode(text) {
      // 处理数字类型的情况
      const qrText = text !== null && text !== undefined ? String(text) : '';

      if (!qrText) {
        console.error('无效的二维码文本:', text);
        this.$message.error('无法生成二维码：无效的编号');
        return;
      }

      const canvas = document.getElementById('qr-canvas');

      if (!canvas) {
        console.error('Canvas元素未找到');
        this.$message.error('生成二维码失败：页面元素未加载');
        return;
      }

      // 清空canvas
      const context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);

      // 生成二维码
      QRCode.toCanvas(canvas, qrText, {
        width: 200,
        margin: 1,
        color: {
          dark: '#000000',
          light: '#ffffff'
        }
      }, (error) => {
        if (error) {
          console.error('生成二维码失败:', error);
          this.$message.error('生成二维码失败');
        } else {
          console.log('二维码生成成功');
        }
      });
    },
    // 下载二维码
    downloadQRCode() {
      if (!this.currentInstructionId) {
        this.$message.warning('没有可下载的二维码');
        return;
      }

      const canvas = document.getElementById('qr-canvas');
      if (!canvas) {
        this.$message.error('找不到二维码图像');
        return;
      }

      try {
        const link = document.createElement('a');
        link.download = `量具二维码_${this.currentInstructionId}.png`;
        link.href = canvas.toDataURL('image/png');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success('二维码下载成功');
      } catch (error) {
        console.error('下载二维码失败:', error);
        this.$message.error('下载二维码失败');
      }
    },
  },
  mounted() {
    this.inquiry()
    this.queryInstructionId()
  }
}
</script>

<style scoped>

</style>